import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public final class JsonUtils {

    public static final Map<Class<?>, Map<String, Boolean>> PR_IGNORE_FIELDS = new ConcurrentHashMap<>();
    public static final ValueFilter DPSVALUE_FILTER = new ValueFilter() {
        @Override
        public Object process(Object o, String propertyName, Object propertyValue) {
            if (propertyValue instanceof ReSerializeModel) {
                return ((ReSerializeModel) propertyValue).reSerialize();
            }
            return propertyValue;
        }
    };
    public static final PropertyFilter DPSPROPERTY_FILTER = new PropertyFilter() {
        @Override
        public boolean apply(Object object, String name, Object value) {
            Class<?> clz = object.getClass();
            PR_IGNORE_FIELDS.putIfAbsent(clz, new ConcurrentHashMap<>());
            Map<String, Boolean> clzIgnoreFields = PR_IGNORE_FIELDS.get(clz);
            if (!clzIgnoreFields.containsKey(name)) {
                Field field = ReflectUtils.getFieldWhatever(clz, name);
                if (field == null)
                    return true;
                clzIgnoreFields.put(name, field.isAnnotationPresent(ClientIgnore.class));
            }
            return !clzIgnoreFields.get(name);
        }
    };
    private JsonUtils(){

    }
    public static String toClientString(Object obj) {
        return JSON.toJSONString(obj, new SerializeFilter[] { DPSVALUE_FILTER, DPSPROPERTY_FILTER }, SerializerFeature.DisableCircularReferenceDetect);
    }


    public static JSONObject toClientJSONObject(Object obj) {
        String s = toClientString(obj);
        return JSON.parseObject(s);
    }
}
